package com.udp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSendThread implements Runnable{

    private DatagramSocket socket = null;
    private BufferedReader reader = null;
    private int fromPort;
    private String toIp;
    private int toPort;

    /**
     *
     * @param fromPort : 本地发送端口
     * @param toIp : 目的IP
     * @param toPort : 目的接收端口
     */
    public TalkSendThread(int fromPort, String toIp, int toPort) {
        this.fromPort = fromPort;
        this.toIp = toIp;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(fromPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.print(Thread.currentThread().getName() + " : ");
                reader = new BufferedReader(new InputStreamReader(System.in));
                String msg = reader.readLine();
                if (msg.trim().length() != 0) {
                    String data = Thread.currentThread().getName() + " : " + msg;
                    //打包发送
                    byte[] dataBytes = data.getBytes();
                    DatagramPacket packet = new DatagramPacket
                            (dataBytes, 0, dataBytes.length, new InetSocketAddress(toIp, toPort));
                    socket.send(packet);
                    if (msg.trim().contains("bye")) {
                        break;
                    }
                } else {
                    System.out.println("消息不能为空！请重新输入。");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
